<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="视频标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入视频标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:videos:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:videos:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:videos:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:videos:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="videosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <!-- 课程名展示（带空值保护） -->
      <el-table-column label="课程名" align="center">
        <template slot-scope="scope">
          {{ scope.row.courses && scope.row.courses.title ? scope.row.courses.title : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="视频顺序" align="center" prop="videoOrder" />
      <el-table-column label="视频标题" align="center" prop="title" />

      <!-- 视频播放列（核心优化） -->
      <el-table-column label="视频播放" align="center" prop="videoUrl" width="300">
        <template slot-scope="scope">
          <div v-if="scope.row && scope.row.videoUrl">
            <!-- 原生 video 标签增强兼容性 -->
            <video
              :src="`https://gzq123.oss-cn-beijing.aliyuncs.com/${scope.row.videoUrl}`"
              width="280"
              height="160"
              controls
              poster="https://cube.elemecdn.com/6/94/4d3ea53c0c954547a9be6b7686bcpng.png"
              style="object-fit: cover; border-radius: 5px; box-shadow: 0 0 5px #ccc;"
            >
              <!-- 多格式源兼容 -->
              <source
                :src="`https://gzq123.oss-cn-beijing.aliyuncs.com/${scope.row.videoUrl}`"
                type="video/mp4"
              />
              <source
                :src="`https://gzq123.oss-cn-beijing.aliyuncs.com/${scope.row.videoUrl}`"
                type="video/ogg"
              />
              <source
                :src="`https://gzq123.oss-cn-beijing.aliyuncs.com/${scope.row.videoUrl}`"
                type="video/webm"
              />
              <!-- 浏览器不支持时的提示 -->
              <p style="color: #f00;">您的浏览器不支持视频播放，请更换为 Chrome/Edge 浏览器</p>
            </video>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:videos:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:videos:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 课程名下拉选择框 -->
        <el-form-item label="课程名" prop="courseId">
          <el-select
            v-model="form.courseId"
            placeholder="请选择课程"
            clearable
            filterable
            @input="val => form.courseId = val + ''"
          >
            <el-option
              v-for="course in coursesList"
              :key="course.id"
              :label="course.title"
              :value="course.id + ''"
            />
          </el-select>
        </el-form-item>

        <!-- 视频文件上传 -->
        <el-form-item label="视频文件" prop="videoUrl">
          <fileUpload
            v-model="form.videoUrl"
            :action="'/common/upload'"
            :fileType="['mp4', 'mov', 'avi', 'flv', 'wmv', 'mkv']"
            :fileSize="1024"
            :limit="1"
            :disabled="isEdit && !form.videoUrl"
            @upload-success="handleFileUpload"
            @remove-file="handleFileRemove"
          />
          <div class="el-form-item__error" v-if="videoUploadError">{{ videoUploadError }}</div>
        </el-form-item>

        <el-form-item label="视频顺序" prop="videoOrder">
          <el-input v-model="form.videoOrder" placeholder="请输入视频顺序" />
        </el-form-item>
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入视频标题" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVideos, getVideos, delVideos, addVideos, updateVideos } from "@/api/course/videos";
import { listCourses } from "@/api/course/courses";
import fileUpload from "@/components/FileUpload";
import Pagination from "@/components/Pagination";
import RightToolbar from "@/components/RightToolbar";

export default {
  name: "Videos",
  components: {
    fileUpload,
    Pagination,
    RightToolbar
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      videosList: [],
      coursesList: [],
      open: false,
      title: "",
      videoUploadError: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
      },
      form: {
        id: null,
        courseId: "",
        videoOrder: null,
        title: null,
        del: 0,
        videoUrl: ""
      },
      rules: {
        courseId: [
          { required: true, message: "课程名不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "视频标题不能为空", trigger: "blur" }
        ],
        videoOrder: [
          { required: true, message: "视频顺序不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "请上传视频文件", trigger: ["blur", "change"] }
        ]
      },
      isEdit: false,
    };
  },
  computed: {
    filteredCourses() {
      if (!this.isEdit) return this.coursesList;
      return this.coursesList.filter(course => course.id + '' !== this.form.courseId);
    }
  },
  created() {
    // 浏览器兼容性提示（IE/旧版浏览器）
    const isIE = navigator.userAgent.match(/MSIE|Trident/);
    if (isIE) {
      this.$message.warning('您的浏览器对视频播放兼容性较差，推荐使用 Chrome 或 Edge 浏览器');
    }
    this.getList();
    this.getCoursesList();
  },
  methods: {
    getList() {
      this.loading = true;
      listVideos(this.queryParams).then(response => {
        this.videosList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCoursesList() {
      listCourses({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.coursesList = response.rows.map(course => ({
          ...course,
          id: course.id + '',
          value: course.id + '',
          label: course.title
        }));
      }).catch(error => {
        console.error("获取课程列表失败：", error);
        this.$message.error("获取课程列表失败，请刷新重试");
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        courseId: "",
        videoOrder: null,
        title: null,
        del: 0,
        videoUrl: ""
      };
      this.videoUploadError = "";
      this.resetForm("form");
      this.isEdit = false;
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程视频关联";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.isEdit = true;
      getVideos(id).then(response => {
        this.form = {
          ...response.data,
          courseId: response.data.courseId + '',
          videoUrl: response.data.videoUrl || ""
        };
        this.open = true;
        this.title = "修改课程视频关联";
      });
    },
    handleFileUpload(url) {
      this.form.videoUrl = url;
      this.videoUploadError = "";
    },
    handleFileRemove() {
      this.form.videoUrl = "";
      if (this.isEdit) {
        this.videoUploadError = "修改时不可删除已上传视频，如需更换请重新上传";
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit && !this.form.videoUrl) {
            this.videoUploadError = "请上传视频文件";
            return false;
          }

          if (this.form.id != null) {
            updateVideos(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVideos(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除课程视频关联编号为"${ids}"的数据项？`).then(() => {
        return delVideos(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download(
        "course/videos/export",
        { ...this.queryParams },
        `videos_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
/* 视频播放器样式优化 */
video {
  border-radius: 8px;
  background-color: #f5f7fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  text-align: right;
}
.el-form-item__error {
  padding-top: 4px;
}
</style>
